package com.imti.contentproviderdemo;

import android.Manifest.permission;
import android.content.ContentResolver;
import android.database.Cursor;
import android.icu.text.DateFormat;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.Telephony.Sms;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.tbruyelle.rxpermissions3.RxPermissions;
import io.reactivex.rxjava3.functions.Consumer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity
{

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new RxPermissions(this)
            .request(permission.READ_SMS,
                permission.READ_CONTACTS,
                permission.WRITE_CONTACTS)
            .subscribe(new Consumer<Boolean>()
            {
                @Override
                public void accept(Boolean aBoolean) throws Throwable
                {
                    if (aBoolean)
                    {
                        initView();
                    }
                }
            });

    }

    private void initView()
    {
        EditText editKeyword = findViewById(R.id.edit_contact_keyword);
        Button btnQueryContact = findViewById(R.id.btn_query_contact);
        TextView textResult = findViewById(R.id.text_query_contact_result);

        btnQueryContact.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
//                String keyword = editKeyword.getText().toString();
//                String result = queryContact(keyword);
//                textResult.setText(result);

                textResult.setText(queryContact(editKeyword.getText().toString()));
            }
        });
    }

    private String queryContact(String nameOrNum)
    {
        ContentResolver cr = getContentResolver();

        Uri uri = Uri.parse(Phone.CONTENT_FILTER_URI + "/" + nameOrNum);

        Cursor cursor = cr.query(uri,
            null, null, null, null);

        cursor.moveToFirst();

        StringBuffer sb = new StringBuffer();

        do
        {
            String contactName =
                cursor.getString(cursor.getColumnIndexOrThrow(Phone.DISPLAY_NAME));
            String contactPhone =
                cursor.getString(cursor.getColumnIndexOrThrow(Phone.NUMBER));

            sb.append("联系人：").append(contactName)
                .append("\t电话：").append(contactPhone)
                .append("\n");

        } while (cursor.moveToNext());

        return sb.toString();
    }

    private void queryAllContact()
    {
        ContentResolver cr = getContentResolver();

        Cursor cursor = cr.query(Phone.CONTENT_URI,
            null, null, null, null);

        cursor.moveToFirst();

        do
        {
            String name =
                cursor.getString(cursor.getColumnIndexOrThrow(Phone.DISPLAY_NAME));
            String phone =
                cursor.getString(cursor.getColumnIndexOrThrow(Phone.NUMBER));

            Log.d(TAG, "联系人：" + name + " 电话：" + phone);

        } while (cursor.moveToNext());
    }

    private void initData()
    {
        //获取ContentResolver
        ContentResolver cr = getContentResolver();

        //通过URI遍历短信数据
        Cursor cursor = cr.query(Sms.CONTENT_URI,
            new String[]{Sms.ADDRESS, Sms.DATE, Sms.TYPE, Sms.BODY},
            null, null, null);

        //游标置顶
        cursor.moveToFirst();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        do
        {
            String phone =
                cursor.getString(cursor.getColumnIndexOrThrow(Sms.ADDRESS));
            String date =
                cursor.getString(cursor.getColumnIndexOrThrow(Sms.DATE));
            String type = cursor.getString(
                cursor.getColumnIndexOrThrow(Sms.TYPE));
            String content =
                cursor.getString(cursor.getColumnIndexOrThrow(Sms.BODY));

            Log.d(TAG,
                "号码：" + phone + " 日期：" + sdf.format(new Date(Long.parseLong(date)))
                    + " 类型：" + type + " 内容：" + content);

        } while (cursor.moveToNext());
    }
}